#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AwaitTransformPass - await 表达式转换阶段

职责：
1. 将复杂的 await 表达式拆分为多个语句
2. 例如：result = await f() + await g() 转换为：
   __await_temp_0 = await f()
   __await_temp_1 = await g()
   result = __await_temp_0 + __await_temp_1

注意：
- 本 pass 只负责表达式拆分，不涉及类型推导
"""

from typing import Any, Dict, Optional, List

from mcpy.ir.module import IRModule
from .base import BasePass, PassStage, PassContext
from ..ir.base import IRNode
from ..ir.declarations import IRFunctionNode, IRMethodNode
from ..ir.expressions.await_expr import IRAwait
from ..ir.expressions.base import IRExpr
from ..ir.expressions.basic import IRName, IRConstant
from ..ir.expressions.operators import IRBinOp, IRBoolOp, IRCompare, IRUnaryOp
from ..ir.expressions.control import IRConditional
from ..ir.expressions.call import IRCall
from ..ir.expressions.access import IRAttribute, IRSubscript
from ..ir.statements import IRAssign, IRStmtBlock, IRReturn, IRExprStmt
from ..ir.statements import IRTryExcept
from ..ir.statements.control import IRIf, IRForEach, IRWhile, IRBreak
from ..ir.expressions.comprehension import IRListComp, IRSetComp, IRDictComp
from ..ir.expressions.literals import IRList, IRDict, IRSet, IRTuple
from ..codegen.utils.await_detector import contains_await


class AwaitTransformPass(BasePass):
    """await 表达式转换 Pass

    将包含 await 的复杂表达式拆分为多个语句。
    """

    name = "await_expression_transform"
    stage = PassStage.PRE_ANALYSIS  # 在类型推导之前运行，确保临时变量能被类型推导

    def __init__(self, config: Optional[Dict[str, Any]] = None):
        super().__init__()
        self.config = config or {}
        # 每个函数独立的临时变量计数器，使用对象ID作为key
        self._temp_var_counters: Dict[int, int] = {}
        # 当前正在处理的函数节点（用于嵌套函数场景）
        self._current_function: Optional[IRNode] = None

    def run(self, ir_module: IRModule, context: PassContext) -> IRNode:
        """运行 await 表达式转换"""
        self._transform_async_functions(ir_module)
        return ir_module

    def _generate_temp_var(self, func_node: Optional[IRNode] = None) -> str:
        """生成临时变量名

        Args:
            func_node: 函数节点，如果为 None 则使用当前正在处理的函数
        """
        # 确定使用哪个函数的计数器
        if func_node is None:
            func_node = self._current_function

        if func_node is None:
            # 如果没有指定函数节点，回退到全局计数器（不应该发生）
            if not hasattr(self, "_fallback_counter"):
                self._fallback_counter = 0
            var_name = f"__await_temp_{self._fallback_counter}"
            self._fallback_counter += 1
            return var_name

        # 使用对象ID作为key
        func_id = id(func_node)

        # 为该函数初始化计数器（如果还没有）
        if func_id not in self._temp_var_counters:
            self._temp_var_counters[func_id] = 0

        # 生成临时变量名并递增计数器
        counter = self._temp_var_counters[func_id]
        var_name = f"__await_temp_{counter}"
        self._temp_var_counters[func_id] = counter + 1
        return var_name

    def _transform_async_functions(self, node: IRNode) -> None:
        """转换 async 函数中的 await 表达式"""
        # 保存之前的当前函数
        prev_function = self._current_function

        if isinstance(node, (IRFunctionNode, IRMethodNode)) and node.is_async:
            # 设置当前正在处理的函数
            self._current_function = node
            # 初始化该函数的计数器
            func_id = id(node)
            if func_id not in self._temp_var_counters:
                self._temp_var_counters[func_id] = 0

            if self._has_await_in_statements(node.body.statements):
                self._transform_function_body(node)
                # 清理该函数节点的符号缓存，因为可能修改了其 IR 结构（添加了临时变量）
                # 确保后续 pass 能够看到新添加的符号
                node.invalidate_symbol_cache()
                # 转换后，需要再次遍历，因为可能添加了新的 IRForEach（从列表推导式转换而来）
                # 这些新的 IRForEach 也需要被转换
                if self._has_await_in_statements(node.body.statements):
                    self._transform_function_body(node)

        for child in node.get_child_nodes():
            self._transform_async_functions(child)

        # 恢复之前的当前函数
        self._current_function = prev_function

    def _has_await_in_statements(self, statements: List[IRNode]) -> bool:
        """检查语句列表中是否包含 await 表达式"""
        for stmt in statements:
            if contains_await(stmt):
                return True
        return False

    def _transform_function_body(self, func_node: IRFunctionNode) -> None:
        """转换函数体中的 await 表达式"""
        if not func_node.body or not func_node.body.statements:
            return

        new_statements = []
        for stmt in func_node.body.statements:
            transformed = self._transform_statement(stmt)
            if isinstance(transformed, list):
                new_statements.extend(transformed)
            else:
                new_statements.append(transformed)

        func_node.body.statements = new_statements

    def _transform_statement(self, stmt: IRNode) -> List[IRNode]:
        """转换单个语句"""
        if isinstance(stmt, IRAssign):
            return self._transform_assignment(stmt)
        elif isinstance(stmt, IRReturn):
            return self._transform_return(stmt)
        elif isinstance(stmt, IRExprStmt):
            return self._transform_expr_stmt(stmt)
        elif isinstance(stmt, IRForEach):
            return self._transform_for_each(stmt)
        elif isinstance(stmt, IRTryExcept):
            return self._transform_try_except(stmt)
        else:
            return [stmt]

    def _transform_assignment(self, stmt: IRAssign) -> List[IRNode]:
        """转换赋值语句"""
        # 检查是否是包含 await 的推导式表达式
        if isinstance(stmt.value, (IRListComp, IRSetComp, IRDictComp)):
            if contains_await(stmt.value):
                # 直接转换，反向类型传播机制会处理类型推导
                return self._transform_comprehension_assignment(stmt)

        # 检查是否是包含 await 的字面量表达式
        if isinstance(stmt.value, (IRList, IRDict, IRSet, IRTuple)):
            if contains_await(stmt.value):
                # 转换字面量赋值，将包含 await 的字面量转换为顺序语句
                return self._transform_literal_assignment(stmt)

        # 特殊处理：元组解包赋值且值是 await 表达式
        # 例如：a, b = await get_tuple()
        # 需要转换为：
        # __await_temp_0 = await get_tuple()
        # a, b = __await_temp_0
        if stmt.is_tuple_unpacking and isinstance(stmt.value, IRAwait):
            # 检查 await 的值中是否还有嵌套的 await
            if contains_await(stmt.value.value):
                # 有嵌套 await，需要先拆分
                return self._split_expression_in_assignment(stmt)
            else:
                # 没有嵌套 await，直接提取到临时变量
                return self._transform_tuple_unpacking_with_await(stmt)

        # 如果右侧是简单的 await 表达式（await 的值中不包含其他 await），不需要拆分
        # 例如：v = await add_one(v)  -> 不拆分
        # 但是：result = await double_value(await get_value(5))  -> 需要拆分
        if isinstance(stmt.value, IRAwait):
            # 检查 await 的值中是否还有嵌套的 await
            if not contains_await(stmt.value.value):
                return [stmt]

        # 如果右侧包含 await（在复合表达式中或嵌套 await），需要拆分
        if contains_await(stmt.value):
            return self._split_expression_in_assignment(stmt)

        return [stmt]

    def _transform_return(self, stmt: IRReturn) -> List[IRNode]:
        """转换 return 语句

        Args:
            stmt: return 语句节点

        Returns:
            转换后的语句列表
        """
        if not stmt.expr:
            return [stmt]

        # 特殊情况：return await func() - 拆分为 __tmp = await func(); return __tmp
        # 这样可以让代码生成阶段复用 await 赋值和 return 的生成逻辑
        if isinstance(stmt.expr, IRAwait):
            # 检查 await 的值中是否还有嵌套的 await
            if contains_await(stmt.expr.value):
                # 有嵌套 await，使用通用拆分逻辑
                return self._split_expression_in_return(stmt)

            # 简单的 return await，直接拆分为两个语句
            temp_var = self._generate_temp_var()
            temp_name = IRName(id=temp_var)
            temp_name.parent = stmt.parent

            # 创建临时变量赋值：__tmp = await func()
            temp_assign = IRAssign()
            temp_assign.target_exprs = [temp_name]
            temp_assign.value = stmt.expr
            temp_assign.parent = stmt.parent
            temp_name.parent = temp_assign
            stmt.expr.parent = temp_assign
            if stmt.source_line is not None:
                temp_assign.source_line = stmt.source_line

            # 创建 return 语句：return __tmp
            return_stmt = IRReturn()
            return_ref = IRName(id=temp_var)
            return_ref.parent = return_stmt
            return_stmt.expr = return_ref
            return_stmt.parent = stmt.parent
            if stmt.source_line is not None:
                return_stmt.source_line = stmt.source_line

            return [temp_assign, return_stmt]

        # 如果返回值包含 await（在复合表达式中或嵌套 await），需要拆分
        if contains_await(stmt.expr):
            return self._split_expression_in_return(stmt)

        return [stmt]

    def _transform_try_except(self, stmt: IRTryExcept) -> List[IRNode]:
        """转换 try/except/finally 语句

        递归转换 try 块、except 块和 finally 块中的 await 表达式。

        Args:
            stmt: try/except/finally 语句节点

        Returns:
            转换后的语句列表（通常只包含原语句，但内部已转换）
        """
        # 转换 try 块
        if stmt.body and stmt.body.statements:
            new_statements = []
            for body_stmt in stmt.body.statements:
                transformed = self._transform_statement(body_stmt)
                if isinstance(transformed, list):
                    new_statements.extend(transformed)
                else:
                    new_statements.append(transformed)
            stmt.body.statements = new_statements

        # 转换 except 处理器
        if stmt.handlers:
            for handler in stmt.handlers:
                if handler.body and handler.body.statements:
                    new_statements = []
                    for handler_stmt in handler.body.statements:
                        transformed = self._transform_statement(handler_stmt)
                        if isinstance(transformed, list):
                            new_statements.extend(transformed)
                        else:
                            new_statements.append(transformed)
                    handler.body.statements = new_statements

        # 转换 else 块
        if stmt.orelse and stmt.orelse.statements:
            new_statements = []
            for else_stmt in stmt.orelse.statements:
                transformed = self._transform_statement(else_stmt)
                if isinstance(transformed, list):
                    new_statements.extend(transformed)
                else:
                    new_statements.append(transformed)
            stmt.orelse.statements = new_statements

        # 转换 finally 块
        if stmt.finalbody and stmt.finalbody.statements:
            new_statements = []
            for finally_stmt in stmt.finalbody.statements:
                transformed = self._transform_statement(finally_stmt)
                if isinstance(transformed, list):
                    new_statements.extend(transformed)
                else:
                    new_statements.append(transformed)
            stmt.finalbody.statements = new_statements

        return [stmt]

    def _transform_expr_stmt(self, stmt: IRExprStmt) -> List[IRNode]:
        """转换表达式语句

        Args:
            stmt: 表达式语句节点

        Returns:
            转换后的语句列表
        """
        if not stmt.expr:
            return [stmt]

        # 如果表达式包含 await，需要拆分
        if contains_await(stmt.expr):
            return self._split_expression_in_expr_stmt(stmt)

        return [stmt]

    def _transform_for_each(self, stmt: IRForEach) -> List[IRNode]:
        """转换 for-each 语句

        如果循环体包含 await，将 for-in 循环转换为迭代器模式：
        for num in numbers:
            await ...
        =>
        it = iter(numbers)
        while True:
            num = next(it, None)
            if not num:
                break
            await ...

        对于元组解包：
        for key, value in d.items():
            await ...
        =>
        it = iter(d.items())
        while True:
            item = next(it, None)
            if not item:
                break
            key, value = item
            await ...

        Args:
            stmt: for-each 语句节点

        Returns:
            转换后的语句列表
        """
        # 检查循环体是否包含 await
        if not stmt.body or not contains_await(stmt.body):
            return [stmt]

        # 生成迭代器变量名
        iter_var = self._generate_temp_var()

        # 判断是否是元组解包
        is_tuple_unpacking = not isinstance(stmt.var, IRName)

        # 如果是元组解包，需要生成临时变量存储 next() 的结果
        if is_tuple_unpacking:
            # 提取元组解包的变量名
            item_var = self._generate_temp_var()
            var_names = self._extract_var_names_from_target(stmt.var)
        else:
            # 简单变量
            if isinstance(stmt.var, IRName):
                item_var = stmt.var.id
                var_names = [stmt.var.id]
            else:
                # 不应该到这里，但为了安全
                item_var = self._generate_temp_var()
                var_names = []

        # 创建语句列表
        new_stmts = []

        # 1. it = iter(numbers)
        iter_call = IRCall()
        iter_call.func = IRName(id="iter")
        iter_call.func.parent = iter_call
        iter_call.args = [stmt.iter_expr]
        iter_call.parent = stmt.parent
        stmt.iter_expr.parent = iter_call

        iter_assign = IRAssign()
        iter_assign.target_exprs = [IRName(id=iter_var)]
        iter_assign.target_exprs[0].parent = iter_assign
        iter_assign.value = iter_call
        iter_assign.parent = stmt.parent
        iter_call.parent = iter_assign
        iter_assign.source_line = stmt.source_line
        new_stmts.append(iter_assign)

        # 2. while True:
        while_stmt = IRWhile()
        while_stmt.test = IRConstant(value=True)
        while_stmt.test.parent = while_stmt
        while_stmt.parent = stmt.parent
        while_stmt.source_line = stmt.source_line

        # 创建 while 循环体
        while_body = IRStmtBlock()
        while_body.parent = while_stmt
        while_stmt.body = while_body

        # 3. item = next(it, None) 或 num = next(it, None)
        next_call = IRCall()
        next_call.func = IRName(id="next")
        next_call.func.parent = next_call
        next_call.args = [IRName(id=iter_var), IRConstant(value=None)]
        next_call.args[0].parent = next_call
        next_call.args[1].parent = next_call
        next_call.parent = while_body

        item_assign = IRAssign()
        item_assign.target_exprs = [IRName(id=item_var)]
        item_assign.target_exprs[0].parent = item_assign
        item_assign.value = next_call
        item_assign.parent = while_body
        next_call.parent = item_assign
        item_assign.source_line = stmt.source_line
        while_body.statements.append(item_assign)

        # 4. if not item: break
        if_stmt = IRIf()
        if_stmt.parent = while_body

        # not item
        not_op = IRUnaryOp()
        not_op.op = "not"
        not_op.operand = IRName(id=item_var)
        not_op.operand.parent = not_op
        not_op.parent = if_stmt
        if_stmt.test = not_op

        # break
        if_stmt.then_body = IRStmtBlock()
        if_stmt.then_body.parent = if_stmt
        break_stmt = IRBreak()
        break_stmt.parent = if_stmt.then_body
        break_stmt.source_line = stmt.source_line
        if_stmt.then_body.statements.append(break_stmt)

        if_stmt.source_line = stmt.source_line
        while_body.statements.append(if_stmt)

        # 5. 如果是元组解包，使用下标操作替代解包语法
        if is_tuple_unpacking:
            from ..ir.expressions.access import IRSubscript

            # 为每个变量生成下标赋值：key = item[0], value = item[1], ...
            for idx, var_name in enumerate(var_names):
                # 创建下标表达式：item[idx]
                subscript = IRSubscript()
                subscript.value = IRName(id=item_var)
                subscript.value.parent = subscript
                subscript.slice = IRConstant(value=idx)
                subscript.slice.parent = subscript
                subscript.parent = while_body

                # 创建赋值：var_name = item[idx]
                var_assign = IRAssign()
                var_assign.target_exprs = [IRName(id=var_name)]
                var_assign.target_exprs[0].parent = var_assign
                var_assign.value = subscript
                subscript.parent = var_assign
                var_assign.parent = while_body
                var_assign.source_line = stmt.source_line

                while_body.statements.append(var_assign)

        # 6. 添加原循环体的语句（递归转换）
        if stmt.body and stmt.body.statements:
            for body_stmt in stmt.body.statements:
                # 更新 parent
                body_stmt.parent = while_body
                # 递归转换
                # 注意：如果 body_stmt 已经是 await 赋值（IRAssign with IRAwait），不应该再次转换
                if isinstance(body_stmt, IRAssign) and isinstance(
                    body_stmt.value, IRAwait
                ):
                    # 已经是 await 赋值，直接添加，不再次转换
                    while_body.statements.append(body_stmt)
                else:
                    transformed = self._transform_statement(body_stmt)
                    while_body.statements.extend(transformed)

        new_stmts.append(while_stmt)
        return new_stmts

    def _var_used_in_expr(
        self, var_name: str, expr: IRNode, visited: Optional[set] = None
    ) -> bool:
        """检查变量是否在表达式中使用"""
        if expr is None:
            return False

        if visited is None:
            visited = set()

        node_id = id(expr)
        if node_id in visited:
            return False
        visited.add(node_id)

        # 检查是否是变量名节点
        if isinstance(expr, IRName) and expr.id == var_name:
            return True

        # 递归检查子节点
        if hasattr(expr, "__dict__"):
            skip_attrs = {"parent", "statements", "body", "then_body", "else_body"}
            for attr_name, attr_value in expr.__dict__.items():
                if attr_name in skip_attrs:
                    continue
                if isinstance(attr_value, list):
                    for item in attr_value:
                        if isinstance(item, IRNode) and self._var_used_in_expr(
                            var_name, item, visited
                        ):
                            return True
                elif isinstance(attr_value, IRNode):
                    if self._var_used_in_expr(var_name, attr_value, visited):
                        return True

        return False

    def _extract_var_names_from_target(self, target: IRNode) -> list[str]:
        """从目标节点中提取所有变量名

        Args:
            target: 目标节点（可能是 IRName、IRTuple 或 IRList）

        Returns:
            变量名列表
        """
        if isinstance(target, IRName):
            return [target.id]
        elif hasattr(target, "elements"):
            # IRTuple 或 IRList
            result = []
            for element in getattr(target, "elements"):
                result.extend(self._extract_var_names_from_target(element))
            return result
        return []

    def _split_expression_in_assignment(self, stmt: IRAssign) -> List[IRNode]:
        """拆分赋值语句中包含 await 的表达式

        支持：
        1. 普通表达式：result = await f() + await g()
        2. 短路求值：result = await f() and await g()
        3. 三元运算符：result = await f() if cond else await g()
        """
        target = stmt.get_target_expr()
        if not target:
            return [stmt]

        # 检查是否需要短路求值处理
        if self._needs_short_circuit_transform(stmt.value):
            return self._split_with_short_circuit(target, stmt.value, stmt.parent)

        # 普通表达式拆分
        new_stmts = []
        new_expr, temp_stmts = self._extract_await_expressions(stmt.value)
        new_stmts.extend(temp_stmts)
        stmt.value = new_expr
        new_stmts.append(stmt)
        return new_stmts

    def _split_expression_in_return(self, stmt: IRReturn) -> List[IRNode]:
        """拆分 return 语句中包含 await 的表达式

        Args:
            stmt: return 语句节点

        Returns:
            拆分后的语句列表
        """
        new_stmts = []

        # 提取所有 await 表达式并替换为临时变量
        new_expr, temp_stmts = self._extract_await_expressions(stmt.expr)
        new_stmts.extend(temp_stmts)

        # 直接修改原语句的表达式
        stmt.expr = new_expr
        new_stmts.append(stmt)

        return new_stmts

    def _split_expression_in_expr_stmt(self, stmt: IRExprStmt) -> List[IRNode]:
        """拆分表达式语句中包含 await 的表达式

        Args:
            stmt: 表达式语句节点

        Returns:
            拆分后的语句列表
        """
        new_stmts = []

        # 如果表达式本身就是 await，直接创建 _ = await ... 语句
        if isinstance(stmt.expr, IRAwait):
            # 检查 await 的参数中是否有嵌套的 await
            if contains_await(stmt.expr.value):
                # 嵌套的 await 需要先提取
                new_inner, temp_stmts = self._extract_await_expressions(stmt.expr.value)
                new_stmts.extend(temp_stmts)
                stmt.expr.value = new_inner
                new_inner.parent = stmt.expr

            # 创建 _ = await ... 语句
            assign = IRAssign()
            discard_target = IRName()
            discard_target.id = "_"
            assign.target_exprs = [discard_target]
            assign.value = stmt.expr
            assign.parent = stmt.parent
            discard_target.parent = assign
            stmt.expr.parent = assign
            new_stmts.append(assign)
            return new_stmts

        # 提取所有 await 表达式并替换为临时变量
        new_expr, temp_stmts = self._extract_await_expressions(stmt.expr)
        new_stmts.extend(temp_stmts)

        # 直接修改原语句的表达式
        stmt.expr = new_expr
        new_stmts.append(stmt)

        return new_stmts

    def _needs_short_circuit_transform(self, expr: IRNode) -> bool:
        """检查表达式是否需要短路求值处理"""
        if isinstance(expr, IRBoolOp) and contains_await(expr):
            # and/or 运算符包含 await
            return True
        if isinstance(expr, IRConditional) and contains_await(expr):
            # 三元运算符包含 await
            return True
        return False

    def _split_with_short_circuit(
        self, target: IRNode, expr: IRNode, parent: Optional[IRNode]
    ) -> List[IRNode]:
        """拆分包含短路求值的表达式

        例如：
        - result = await f() and await g()
          转换为：
          __await_temp_0 = await f()
          if __await_temp_0:
              __await_temp_1 = await g()
              result = __await_temp_1
          else:
              result = __await_temp_0

        - result = await f() or await g()
          转换为：
          __await_temp_0 = await f()
          if __await_temp_0:
              result = __await_temp_0
          else:
              __await_temp_1 = await g()
              result = __await_temp_1

        - result = await f() if cond else await g()
          转换为：
          if cond:
              __await_temp_0 = await f()
              result = __await_temp_0
          else:
              __await_temp_1 = await g()
              result = __await_temp_1
        """
        if isinstance(expr, IRBoolOp):
            return self._split_boolop_with_short_circuit(target, expr, parent)
        elif isinstance(expr, IRConditional):
            return self._split_conditional_with_short_circuit(target, expr, parent)
        else:
            # 不应该走到这里
            return []

    def _split_boolop_with_short_circuit(
        self, target: IRNode, boolop: IRBoolOp, parent: Optional[IRNode]
    ) -> List[IRNode]:
        """拆分布尔运算符表达式（and/or）

        转换策略：
        result = await f() and await g()
        =>
        result = await f()
        if result:
            result = await g()

        result = await f() or await g()
        =>
        result = await f()
        if not result:
            result = await g()
        """
        if len(boolop.values) < 2:
            return []

        new_stmts = []
        is_and = boolop.op == "and"

        # 第一步：将第一个操作数赋值给 target
        first_value = boolop.values[0]
        first_assign_stmts = self._create_assignment_with_await(
            target, first_value, parent
        )
        new_stmts.extend(first_assign_stmts)

        # 第二步：根据 target 的值决定是否计算剩余操作数
        if len(boolop.values) == 2:
            # 只有两个操作数
            second_value = boolop.values[1]
            if_stmts = self._create_conditional_assignment(
                target, second_value, is_and, parent
            )
            new_stmts.extend(if_stmts)
        else:
            # 多个操作数，递归处理
            remaining_boolop = IRBoolOp()
            remaining_boolop.op = boolop.op
            remaining_boolop.values = boolop.values[1:]
            remaining_boolop.parent = parent

            if_stmts = self._create_conditional_assignment(
                target, remaining_boolop, is_and, parent
            )
            new_stmts.extend(if_stmts)

        return new_stmts

    def _split_conditional_with_short_circuit(
        self, target: IRNode, cond_expr: IRConditional, parent: Optional[IRNode]
    ) -> List[IRNode]:
        """拆分三元运算符表达式

        result = await f() if cond else await g()
        转换为：
        if cond:
            __await_temp_0 = await f()
            result = __await_temp_0
        else:
            __await_temp_1 = await g()
            result = __await_temp_1

        注意：遵循 Python 语义，不提前声明 result，
        在两个分支中都是声明（第一次）或赋值（后续）
        """
        new_stmts = []

        # 如果条件包含 await，先拆分条件
        test_expr = cond_expr.test
        if contains_await(test_expr):
            # 提取 await 表达式，避免创建多余的临时变量
            # 例如：await get_true() -> __await_temp_X = await get_true()
            new_test_expr, temp_stmts = self._extract_await_expressions(test_expr)
            new_stmts.extend(temp_stmts)
            test_ref = new_test_expr  # 直接使用提取后的变量引用
        else:
            test_ref = test_expr

        # 创建 if 语句
        if_stmt = IRIf()
        if_stmt.test = test_ref
        if_stmt.parent = parent

        # 设置测试表达式的 parent
        test_ref.parent = if_stmt

        # then 分支：处理 body
        then_body = IRStmtBlock()
        then_body.parent = if_stmt
        if_stmt.then_body = then_body

        body_stmts = self._create_branch_assignment(target, cond_expr.body, then_body)
        then_body.statements = body_stmts

        # else 分支：处理 orelse
        else_body = IRStmtBlock()
        else_body.parent = if_stmt
        if_stmt.else_body = else_body

        orelse_stmts = self._create_branch_assignment(
            target, cond_expr.orelse, else_body
        )
        else_body.statements = orelse_stmts

        new_stmts.append(if_stmt)
        return new_stmts

    def _create_short_circuit_if(
        self,
        target: IRNode,
        first_value: IRNode,
        second_value: IRNode,
        is_and: bool,
        parent: Optional[IRNode],
    ) -> List[IRNode]:
        """创建短路求值的 if 语句

        Args:
            target: 赋值目标
            first_value: 第一个操作数（已求值）
            second_value: 第二个操作数
            is_and: True 表示 and，False 表示 or
            parent: 父节点
        """
        if_stmt = IRIf()
        if_stmt.test = first_value
        if_stmt.parent = parent

        # 设置测试表达式的 parent
        first_value.parent = if_stmt

        # then 分支和 else 分支根据 and/or 不同
        then_body = IRStmtBlock()
        then_body.parent = if_stmt
        if_stmt.then_body = then_body

        else_body = IRStmtBlock()
        else_body.parent = if_stmt
        if_stmt.else_body = else_body

        if is_and:
            # and: if first_value: result = second_value else: result = first_value
            then_stmts = self._create_branch_assignment(target, second_value, then_body)
            then_body.statements = then_stmts

            else_stmts = self._create_simple_assignment(target, first_value, else_body)
            else_body.statements = else_stmts
        else:
            # or: if first_value: result = first_value else: result = second_value
            then_stmts = self._create_simple_assignment(target, first_value, then_body)
            then_body.statements = then_stmts

            else_stmts = self._create_branch_assignment(target, second_value, else_body)
            else_body.statements = else_stmts

        return [if_stmt]

    def _create_assignment_with_await(
        self, target: IRNode, value: IRNode, parent: Optional[IRNode]
    ) -> List[IRNode]:
        """创建赋值语句（可能包含 await）

        优化策略：
        - 如果 value 本身就是顶层的 await 表达式，直接生成 target = await f()
        - 只有当 await 在嵌套位置时，才需要提取临时变量

        Args:
            target: 赋值目标
            value: 赋值的值（可能包含 await）
            parent: 父节点

        Returns:
            语句列表
        """
        stmts = []

        # 优化：如果 value 本身就是 IRAwait，直接创建赋值，不需要临时变量
        # 但需要先处理 await 内部可能的嵌套 await
        if isinstance(value, IRAwait):
            # 检查 await 的参数中是否有嵌套的 await
            if contains_await(value.value):
                # 嵌套的 await 需要先提取
                new_inner, temp_stmts = self._extract_await_expressions(value.value)
                for temp_stmt in temp_stmts:
                    temp_stmt.parent = parent
                stmts.extend(temp_stmts)
                value.value = new_inner
                new_inner.parent = value

            # 直接创建 target = await ...
            assign = IRAssign()
            cloned_target = self._clone_name(target)
            assign.target_exprs = [cloned_target]
            assign.value = value
            assign.parent = parent
            cloned_target.parent = assign
            value.parent = assign
            stmts.append(assign)
            return stmts

        # 对于非 await 的表达式，如果包含 await，需要先拆分
        if contains_await(value):
            new_value, temp_stmts = self._extract_await_expressions(value)
            # 设置临时语句的 parent
            for temp_stmt in temp_stmts:
                temp_stmt.parent = parent
            stmts.extend(temp_stmts)
            value = new_value

        # 创建赋值语句：target = value
        assign = IRAssign()
        cloned_target = self._clone_name(target)
        assign.target_exprs = [cloned_target]
        assign.value = value
        assign.parent = parent

        # 设置子节点的 parent（关键！）
        cloned_target.parent = assign
        value.parent = assign

        stmts.append(assign)
        return stmts

    def _create_conditional_assignment(
        self, target: IRNode, value: IRNode, is_and: bool, parent: Optional[IRNode]
    ) -> List[IRNode]:
        """创建条件赋值语句

        对于 and：if target: target = value
        对于 or：if not target: target = value

        Args:
            target: 赋值目标
            value: 赋值的值
            is_and: True 表示 and，False 表示 or
            parent: 父节点

        Returns:
            语句列表（包含 if 语句）
        """
        # 创建 if 语句
        if_stmt = IRIf()
        if_stmt.parent = parent

        # 创建测试条件：target 或 not target
        test_expr = self._clone_name(target)
        test_expr.parent = if_stmt

        if not is_and:
            # or 运算符：if not target
            unary_op = IRUnaryOp()
            unary_op.op = "not"
            unary_op.operand = test_expr
            unary_op.parent = if_stmt
            test_expr.parent = unary_op
            if_stmt.test = unary_op
        else:
            # and 运算符：if target
            if_stmt.test = test_expr

        # 创建 then 分支：target = value
        then_body = IRStmtBlock()
        then_body.parent = if_stmt
        if_stmt.then_body = then_body

        # 在 then 分支中创建赋值语句
        assign_stmts = self._create_assignment_with_await(target, value, then_body)
        then_body.statements = assign_stmts

        return [if_stmt]

    def _create_branch_assignment(
        self, target: IRNode, value: IRNode, parent: Optional[IRNode]
    ) -> List[IRNode]:
        """创建分支中的赋值语句

        如果 value 包含 await，先拆分，然后赋值
        如果 value 不包含 await，直接赋值

        优化：直接使用 _create_assignment_with_await，它已经处理了：
        - 顶层 await 表达式：直接赋值给 target，不创建额外临时变量
        - 嵌套 await 表达式：只提取嵌套的部分
        """
        if contains_await(value):
            # 使用优化后的方法，避免创建多余的临时变量
            return self._create_assignment_with_await(target, value, parent)
        else:
            # 不包含 await，直接赋值
            return self._create_simple_assignment(target, value, parent)

    def _create_simple_assignment(
        self, target: IRNode, value: IRNode, parent: Optional[IRNode]
    ) -> List[IRNode]:
        """创建简单赋值语句：target = value"""
        assign = IRAssign()
        cloned_target = self._clone_name(target)
        assign.target_exprs = [cloned_target]
        assign.parent = parent

        # 设置 target 的 parent（关键！）
        cloned_target.parent = assign

        # 如果 value 是 IRName，需要克隆它并设置 parent
        if isinstance(value, IRName):
            cloned_value = self._clone_name(value)
            cloned_value.parent = assign
            assign.value = cloned_value
        else:
            assign.value = value
            value.parent = assign

        return [assign]

    def _create_temp_assignment(
        self, temp_var: str, value: IRNode, parent: Optional[IRNode] = None
    ) -> List[IRNode]:
        """创建临时变量赋值：__temp_N = value

        如果 value 包含 await，会递归拆分

        Args:
            temp_var: 临时变量名
            value: 要赋值的表达式
            parent: 父节点（可选）
        """
        stmts = []
        new_value, temp_stmts = self._extract_await_expressions(value)
        stmts.extend(temp_stmts)

        # 创建赋值：temp_var = new_value
        assign = IRAssign()
        assign.target_exprs = [self._create_name_ref(temp_var)]
        assign.value = new_value
        assign.parent = parent  # 设置父节点
        stmts.append(assign)

        return stmts

    def _transform_tuple_unpacking_with_await(self, stmt: IRAssign) -> List[IRNode]:
        """转换元组解包赋值且值是 await 表达式的情况

        例如：a, b = await get_tuple()
        转换为：
        __await_temp_0 = await get_tuple()
        a, b = __await_temp_0

        Args:
            stmt: 元组解包赋值语句（值是 IRAwait）

        Returns:
            转换后的语句列表
        """
        new_stmts = []

        # 1. 生成临时变量并提取 await 表达式
        temp_var = self._generate_temp_var()
        temp_name = IRName(id=temp_var)
        temp_name.parent = stmt.parent

        # 创建临时变量赋值：__await_temp_0 = await get_tuple()
        temp_assign_stmts = self._create_assignment_with_await(
            temp_name, stmt.value, stmt.parent
        )
        new_stmts.extend(temp_assign_stmts)

        # 2. 创建新的元组解包赋值：a, b = __await_temp_0
        new_assign = IRAssign()
        # 复制目标表达式
        new_assign.target_exprs = []
        for target_expr in stmt.target_exprs:
            cloned_target = self._clone_name(target_expr)
            cloned_target.parent = new_assign
            new_assign.target_exprs.append(cloned_target)
        new_assign.is_tuple_unpacking = True
        # 使用临时变量作为值
        temp_ref = IRName(id=temp_var)
        temp_ref.parent = new_assign
        new_assign.value = temp_ref
        new_assign.parent = stmt.parent
        new_assign.annotation = stmt.annotation
        if stmt.source_line is not None:
            new_assign.source_line = stmt.source_line

        new_stmts.append(new_assign)

        return new_stmts

    def _create_name_ref(self, name: str) -> IRName:
        """创建名称引用"""
        ref = IRName()
        ref.id = name
        return ref

    def _clone_name(self, name: IRNode) -> IRName:
        """克隆名称节点

        注意：这里创建一个新的 IRName 节点，但不复制符号信息。
        新节点会在后续的类型推导阶段重新创建符号。
        """
        if isinstance(name, IRName):
            new_name = IRName()
            new_name.id = name.id
            new_name.source_line = name.source_line
            return new_name
        else:
            # 如果不是 IRName，创建一个默认的
            return IRName()

    def _extract_await_expressions(self, expr: Optional[IRNode]) -> tuple:
        """从表达式中提取 await 表达式，替换为临时变量"""
        if expr is None:
            return None, []

        temp_stmts = []
        new_expr = self._extract_await_stmt(expr, temp_stmts)
        return new_expr, temp_stmts

    def _extract_await_stmt(self, expr: IRNode, temp_stmts: List[IRNode]) -> IRNode:
        """递归提取 await 表达式"""
        if isinstance(expr, IRAwait):
            new_value = self._extract_await_stmt(expr.value, temp_stmts)
            if isinstance(new_value, IRExpr):
                expr.value = new_value
            else:
                pass

            # 创建临时变量
            temp_var = self._generate_temp_var()

            # 创建临时赋值语句：__temp_N = await expr
            temp_target = IRName()
            temp_target.id = temp_var

            temp_assign = IRAssign()
            temp_assign.target_exprs = [temp_target]
            temp_assign.value = expr
            temp_assign.parent = expr.parent
            temp_target.parent = temp_assign

            temp_stmts.append(temp_assign)

            # 返回临时变量引用
            temp_ref = IRName()
            temp_ref.id = temp_var
            temp_ref.parent = expr.parent

            return temp_ref

        elif isinstance(expr, IRBinOp):
            # 递归处理左右操作数
            new_left = self._extract_await_stmt(expr.left, temp_stmts)
            new_right = self._extract_await_stmt(expr.right, temp_stmts)

            # 直接修改原节点
            expr.left = new_left
            expr.right = new_right
            return expr

        elif isinstance(expr, IRUnaryOp):
            # 递归处理操作数
            new_operand = self._extract_await_stmt(expr.operand, temp_stmts)

            # 直接修改原节点
            expr.operand = new_operand
            return expr

        elif isinstance(expr, IRCall):
            # 递归处理函数本身（可能是 await f）
            if contains_await(expr.func):
                new_func = self._extract_await_stmt(expr.func, temp_stmts)
                expr.func = new_func

            # 递归处理所有参数（按左到右顺序）
            new_args = []
            for arg in expr.args:
                new_arg = self._extract_await_stmt(arg, temp_stmts)
                new_args.append(new_arg)

            # 直接修改原节点
            expr.args = new_args
            return expr

        elif isinstance(expr, IRBoolOp):
            # 递归处理所有操作数
            new_values = []
            for value in expr.values:
                new_value = self._extract_await_stmt(value, temp_stmts)
                new_values.append(new_value)

            # 直接修改原节点
            expr.values = new_values
            return expr

        elif isinstance(expr, IRCompare):
            # 递归处理左操作数和所有比较器
            new_left = self._extract_await_stmt(expr.left, temp_stmts)
            new_comparators = []
            for comp in expr.comparators:
                new_comp = self._extract_await_stmt(comp, temp_stmts)
                new_comparators.append(new_comp)

            # 直接修改原节点
            expr.left = new_left
            expr.comparators = new_comparators
            return expr

        elif isinstance(expr, IRConditional):
            # 递归处理条件和两个分支
            new_test = self._extract_await_stmt(expr.test, temp_stmts)
            new_body = self._extract_await_stmt(expr.body, temp_stmts)
            new_orelse = self._extract_await_stmt(expr.orelse, temp_stmts)

            # 直接修改原节点
            expr.test = new_test
            expr.body = new_body
            expr.orelse = new_orelse
            return expr

        elif isinstance(expr, IRList):
            # 递归处理列表元素中的 await 表达式
            # 注意：保持 parent 关系，确保代码生成时能正确识别上下文
            original_parent = expr.parent
            new_elements = []
            for element in expr.elements:
                new_element = self._extract_await_stmt(element, temp_stmts)
                new_elements.append(new_element)
            expr.elements = new_elements
            # 确保 parent 关系保持不变
            if original_parent:
                expr.parent = original_parent
            return expr

        elif isinstance(expr, IRDict):
            # 递归处理字典的键和值中的 await 表达式
            # 注意：保持 parent 关系，确保代码生成时能正确识别上下文
            original_parent = expr.parent
            new_keys = []
            for key in expr.keys:
                new_key = self._extract_await_stmt(key, temp_stmts)
                new_keys.append(new_key)
            expr.keys = new_keys

            new_values = []
            for value in expr.values:
                new_value = self._extract_await_stmt(value, temp_stmts)
                new_values.append(new_value)
            expr.values = new_values
            # 确保 parent 关系保持不变
            if original_parent:
                expr.parent = original_parent
            return expr

        elif isinstance(expr, IRSet):
            # 递归处理集合元素中的 await 表达式
            # 注意：保持 parent 关系，确保代码生成时能正确识别上下文
            original_parent = expr.parent
            new_elements = []
            for element in expr.elements:
                new_element = self._extract_await_stmt(element, temp_stmts)
                new_elements.append(new_element)
            expr.elements = new_elements
            # 确保 parent 关系保持不变
            if original_parent:
                expr.parent = original_parent
            return expr

        elif isinstance(expr, IRTuple):
            # 递归处理元组元素中的 await 表达式
            # 注意：保持 parent 关系，确保代码生成时能正确识别上下文
            original_parent = expr.parent
            new_elements = []
            for element in expr.elements:
                new_element = self._extract_await_stmt(element, temp_stmts)
                new_elements.append(new_element)
            expr.elements = new_elements
            # 确保 parent 关系保持不变
            if original_parent:
                expr.parent = original_parent
            return expr

        else:
            # 其他类型的表达式，直接返回
            return expr

    def _transform_comprehension_assignment(self, stmt: IRAssign) -> List[IRNode]:
        """转换包含 await 的推导式赋值语句

        将异步列表推导式转换为 for 循环：
        result = [await get_value(x) for x in numbers]
        =>
        result = []
        for x in numbers:
            result.append(await get_value(x))

        支持：
        1. 基础列表推导式：单生成器，无条件
        2. 带条件的列表推导式：单生成器，单条件
        3. 嵌套列表推导式：多个生成器
        4. 迭代对象中包含 await：await get_list()
        5. 条件中包含 await：if await check_even(x)

        Args:
            stmt: 赋值语句节点

        Returns:
            转换后的语句列表
        """
        comp_expr = stmt.value
        target = stmt.get_target_expr()

        if target is None:
            # 无法获取目标，返回原语句
            return [stmt]

        if isinstance(comp_expr, IRListComp):
            new_stmts = self._transform_list_comp_to_for_loop(
                target, comp_expr, stmt.parent
            )
        elif isinstance(comp_expr, IRSetComp):
            new_stmts = self._transform_set_comp_to_for_loop(
                target, comp_expr, stmt.parent
            )
        elif isinstance(comp_expr, IRDictComp):
            new_stmts = self._transform_dict_comp_to_for_loop(
                target, comp_expr, stmt.parent
            )
        else:
            # 不应该到这里
            return [stmt]

        if len(new_stmts) > 0:
            first_stmt = new_stmts[0]
            if isinstance(first_stmt, IRAssign):
                first_stmt.annotation = stmt.annotation
        return new_stmts

    def _transform_list_comp_to_for_loop(
        self, target: IRNode, list_comp: IRListComp, parent: Optional[IRNode]
    ) -> List[IRNode]:
        """将异步列表推导式转换为 for 循环

        Args:
            target: 赋值目标（result）
            list_comp: 列表推导式节点
            parent: 父节点

        Returns:
            转换后的语句列表
        """
        new_stmts = []

        # 1. 初始化结果列表：result = []
        from ..ir.expressions.literals import IRList

        empty_list = IRList()
        empty_list.parent = parent
        empty_list.elements = []

        init_assign = IRAssign()
        cloned_target = self._clone_name(target)
        init_assign.target_exprs = [cloned_target]
        init_assign.value = empty_list
        init_assign.parent = parent
        cloned_target.parent = init_assign
        empty_list.parent = init_assign
        if list_comp.source_line is not None:
            init_assign.source_line = list_comp.source_line
        new_stmts.append(init_assign)

        # 2. 构建嵌套的 for 循环
        loop_body = self._build_comprehension_loop_body(
            list_comp.generators, list_comp.elt, target, parent, list_comp.source_line
        )

        new_stmts.extend(loop_body)

        return new_stmts

    def _build_comprehension_loop_body(
        self,
        generators: List,
        elt: IRNode,
        result_target: IRNode,
        parent: Optional[IRNode],
        source_line: Optional[int],
    ) -> List[IRNode]:
        """构建推导式的循环体

        递归处理嵌套生成器，构建嵌套的 for 循环。

        Args:
            generators: 生成器列表
            elt: 元素表达式
            result_target: 结果目标变量
            parent: 父节点
            source_line: 源代码行号

        Returns:
            循环语句列表
        """
        if not generators:
            # 没有生成器，直接添加元素
            return self._build_element_append(elt, result_target, parent, source_line)

        # 处理第一个生成器
        gen = generators[0]
        remaining_generators = generators[1:]

        # 检查迭代对象是否包含 await
        iter_expr = gen.iter
        if contains_await(iter_expr):
            # 需要先提取 await
            iter_temp_var = self._generate_temp_var()
            iter_assign_stmts = self._create_temp_assignment(
                iter_temp_var, iter_expr, parent
            )
            iter_expr = IRName(id=iter_temp_var)
            iter_expr.parent = parent
        else:
            iter_assign_stmts = []

        # 由于循环体中包含 await，直接生成 while + 迭代器版本，而不是 for-each
        # 这样可以避免后续再次转换

        # 生成迭代器变量名
        iter_var = self._generate_temp_var()

        # 判断是否是元组解包
        is_tuple_unpacking = not isinstance(gen.target, IRName)

        # 如果是元组解包，需要生成临时变量存储 next() 的结果
        if is_tuple_unpacking:
            # 提取元组解包的变量名
            item_var = self._generate_temp_var()
            var_names = self._extract_var_names_from_target(gen.target)
        else:
            # 简单变量
            if isinstance(gen.target, IRName):
                item_var = gen.target.id
                var_names = [gen.target.id]
            else:
                # 不应该到这里，但为了安全
                item_var = self._generate_temp_var()
                var_names = []

        # 1. it = iter(iter_expr)
        iter_call = IRCall()
        iter_call.func = IRName(id="iter")
        iter_call.func.parent = iter_call
        iter_call.args = [iter_expr]
        iter_call.parent = parent
        iter_expr.parent = iter_call

        iter_assign = IRAssign()
        iter_assign.target_exprs = [IRName(id=iter_var)]
        iter_assign.target_exprs[0].parent = iter_assign
        iter_assign.value = iter_call
        iter_assign.parent = parent
        iter_call.parent = iter_assign
        if source_line is not None:
            iter_assign.source_line = source_line

        # 2. while True:
        while_stmt = IRWhile()
        while_stmt.test = IRConstant(value=True)
        while_stmt.test.parent = while_stmt
        while_stmt.parent = parent
        if source_line is not None:
            while_stmt.source_line = source_line

        # 创建 while 循环体
        loop_body = IRStmtBlock()
        loop_body.parent = while_stmt
        while_stmt.body = loop_body

        # 3. item = next(it, None) 或 x = next(it, None)
        next_call = IRCall()
        next_call.func = IRName(id="next")
        next_call.func.parent = next_call
        next_call.args = [IRName(id=iter_var), IRConstant(value=None)]
        next_call.args[0].parent = next_call
        next_call.args[1].parent = next_call
        next_call.parent = loop_body

        item_assign = IRAssign()
        item_assign.target_exprs = [IRName(id=item_var)]
        item_assign.target_exprs[0].parent = item_assign
        item_assign.value = next_call
        item_assign.parent = loop_body
        next_call.parent = item_assign
        if source_line is not None:
            item_assign.source_line = source_line
        loop_body.statements.append(item_assign)

        # 4. if not item: break
        if_stmt = IRIf()
        if_stmt.parent = loop_body

        # not item
        not_op = IRUnaryOp()
        not_op.op = "not"
        not_op.operand = IRName(id=item_var)
        not_op.operand.parent = not_op
        not_op.parent = if_stmt
        if_stmt.test = not_op

        # break
        if_stmt.then_body = IRStmtBlock()
        if_stmt.then_body.parent = if_stmt
        break_stmt = IRBreak()
        break_stmt.parent = if_stmt.then_body
        if source_line is not None:
            break_stmt.source_line = source_line
        if_stmt.then_body.statements.append(break_stmt)

        if source_line is not None:
            if_stmt.source_line = source_line
        loop_body.statements.append(if_stmt)

        # 5. 如果是元组解包，使用下标操作替代解包语法
        if is_tuple_unpacking:
            from ..ir.expressions.access import IRSubscript

            # 为每个变量生成下标赋值：key = item[0], value = item[1], ...
            for idx, var_name in enumerate(var_names):
                # 创建下标表达式：item[idx]
                subscript = IRSubscript()
                subscript.value = IRName(id=item_var)
                subscript.value.parent = subscript
                subscript.slice = IRConstant(value=idx)
                subscript.slice.parent = subscript
                subscript.parent = loop_body

                # 创建赋值：var_name = item[idx]
                var_assign = IRAssign()
                var_assign.target_exprs = [IRName(id=var_name)]
                var_assign.target_exprs[0].parent = var_assign
                var_assign.value = subscript
                subscript.parent = var_assign
                var_assign.parent = loop_body
                if source_line is not None:
                    var_assign.source_line = source_line

                loop_body.statements.append(var_assign)

        # 处理条件
        if gen.ifs:
            # 有条件，需要先检查条件
            cond_assign_stmts, if_stmt = self._build_condition_check(
                gen.ifs,
                remaining_generators,
                elt,
                result_target,
                loop_body,
                source_line,
            )
            # 先添加条件赋值语句（在 if 之前）
            loop_body.statements.extend(cond_assign_stmts)
            if if_stmt is not None:
                loop_body.statements.append(if_stmt)
        else:
            # 无条件，直接处理剩余生成器或元素
            if remaining_generators:
                # 还有剩余生成器，递归处理
                nested_loops = self._build_comprehension_loop_body(
                    remaining_generators, elt, result_target, loop_body, source_line
                )
                loop_body.statements.extend(nested_loops)
            else:
                # 没有剩余生成器，添加元素
                append_stmts = self._build_element_append(
                    elt, result_target, loop_body, source_line
                )
                loop_body.statements.extend(append_stmts)

        # 组合语句：先处理迭代对象（如果有 await），然后添加迭代器初始化和 while 循环
        result = []
        result.extend(iter_assign_stmts)
        result.append(iter_assign)  # it = iter(...)
        result.append(while_stmt)  # while True: ...

        return result

    def _build_condition_check(
        self,
        conditions: List,
        remaining_generators: List,
        elt: IRNode,
        result_target: IRNode,
        parent: Optional[IRNode],
        source_line: Optional[int],
    ) -> tuple[List[IRNode], Optional[IRIf]]:
        """构建条件检查

        处理多个条件，构建嵌套的 if 语句。

        Args:
            conditions: 条件列表
            remaining_generators: 剩余生成器列表
            elt: 元素表达式
            result_target: 结果目标变量
            parent: 父节点
            source_line: 源代码行号

        Returns:
            (条件赋值语句列表, if 语句节点) 的元组，如果没有条件则返回 ([], None)
        """
        if not conditions:
            # 没有条件，不应该到这里
            return [], None

        # 处理第一个条件
        condition = conditions[0]
        remaining_conditions = conditions[1:]

        # 检查条件是否包含 await
        if contains_await(condition):
            # 需要先提取 await
            cond_temp_var = self._generate_temp_var()
            cond_temp_name = IRName(id=cond_temp_var)
            cond_temp_name.parent = parent
            cond_assign_stmts = self._create_assignment_with_await(
                cond_temp_name, condition, parent
            )
            cond_expr = IRName(id=cond_temp_var)
            cond_expr.parent = parent
        else:
            cond_assign_stmts = []
            cond_expr = condition
            cond_expr.parent = parent

        # 创建 if 语句
        if_stmt = IRIf()
        if_stmt.test = cond_expr
        if_stmt.parent = parent
        if source_line is not None:
            if_stmt.source_line = source_line

        # then 分支：条件为真时，处理剩余条件或剩余生成器或元素
        then_body = IRStmtBlock()
        then_body.parent = if_stmt
        if_stmt.then_body = then_body

        # 注意：条件赋值语句不应该放在 then_body 中，应该在 if 之前执行
        # 所以这里不再添加 cond_assign_stmts 到 then_body

        if remaining_conditions:
            # 还有剩余条件，递归处理
            nested_cond_stmts, nested_if = self._build_condition_check(
                remaining_conditions,
                remaining_generators,
                elt,
                result_target,
                then_body,
                source_line,
            )
            # 嵌套条件的赋值语句应该放在 then_body 中（在 if 之前）
            then_body.statements.extend(nested_cond_stmts)
            if nested_if:
                then_body.statements.append(nested_if)
        elif remaining_generators:
            # 没有剩余条件，但有剩余生成器
            nested_loops = self._build_comprehension_loop_body(
                remaining_generators, elt, result_target, then_body, source_line
            )
            then_body.statements.extend(nested_loops)
        else:
            # 没有剩余条件和生成器，添加元素
            append_stmts = self._build_element_append(
                elt, result_target, then_body, source_line
            )
            then_body.statements.extend(append_stmts)

        return cond_assign_stmts, if_stmt

    def _build_element_append(
        self,
        elt: IRNode,
        result_target: IRNode,
        parent: Optional[IRNode],
        source_line: Optional[int],
    ) -> List[IRNode]:
        """构建元素追加语句

        将元素表达式追加到结果列表中。
        如果元素表达式包含 await，需要先提取 await。

        Args:
            elt: 元素表达式
            result_target: 结果目标变量
            parent: 父节点
            source_line: 源代码行号

        Returns:
            语句列表
        """
        stmts = []

        # 检查元素表达式是否包含 await
        if contains_await(elt):
            # 使用 _create_assignment_with_await 来正确处理 await 表达式
            # 这会保留顶层的 await，只提取嵌套的 await
            elt_temp_var = self._generate_temp_var()
            elt_temp_name = IRName(id=elt_temp_var)
            elt_temp_name.parent = parent

            elt_assign_stmts = self._create_assignment_with_await(
                elt_temp_name, elt, parent
            )

            stmts.extend(elt_assign_stmts)
            elt_expr = elt_temp_name
        else:
            elt_expr = elt
            elt_expr.parent = parent

        # 创建 append 调用：result.append(elt)
        append_call = IRCall()
        append_call.func = IRAttribute()
        append_call.func.value = self._clone_name(result_target)
        append_call.func.value.parent = append_call.func
        append_call.func.attr = "append"
        append_call.func.parent = append_call
        append_call.args = [elt_expr]
        elt_expr.parent = append_call
        append_call.parent = parent

        # 创建表达式语句
        append_stmt = IRExprStmt()
        append_stmt.expr = append_call
        append_call.parent = append_stmt
        append_stmt.parent = parent
        if source_line is not None:
            append_stmt.source_line = source_line

        stmts.append(append_stmt)

        return stmts

    def _build_element_add(
        self,
        elt: IRNode,
        result_target: IRNode,
        parent: Optional[IRNode],
        source_line: Optional[int],
    ) -> List[IRNode]:
        """构建元素添加语句

        将元素表达式添加到结果集合中。
        如果元素表达式包含 await，需要先提取 await。

        Args:
            elt: 元素表达式
            result_target: 结果目标变量
            parent: 父节点
            source_line: 源代码行号

        Returns:
            语句列表
        """
        stmts = []

        # 检查元素表达式是否包含 await
        if contains_await(elt):
            # 使用 _create_assignment_with_await 来正确处理 await 表达式
            # 这会保留顶层的 await，只提取嵌套的 await
            elt_temp_var = self._generate_temp_var()
            elt_temp_name = IRName(id=elt_temp_var)
            elt_temp_name.parent = parent

            elt_assign_stmts = self._create_assignment_with_await(
                elt_temp_name, elt, parent
            )

            stmts.extend(elt_assign_stmts)
            elt_expr = elt_temp_name
        else:
            elt_expr = elt
            elt_expr.parent = parent

        # 创建 add 调用：result.add(elt)
        add_call = IRCall()
        add_call.func = IRAttribute()
        add_call.func.value = self._clone_name(result_target)
        add_call.func.value.parent = add_call.func
        add_call.func.attr = "add"
        add_call.func.parent = add_call
        add_call.args = [elt_expr]
        elt_expr.parent = add_call
        add_call.parent = parent

        # 创建表达式语句
        add_stmt = IRExprStmt()
        add_stmt.expr = add_call
        add_call.parent = add_stmt
        add_stmt.parent = parent
        if source_line is not None:
            add_stmt.source_line = source_line

        stmts.append(add_stmt)

        return stmts

    def _transform_set_comp_to_for_loop(
        self, target: IRNode, set_comp: IRSetComp, parent: Optional[IRNode]
    ) -> List[IRNode]:
        """将异步集合推导式转换为 for 循环

        Args:
            target: 赋值目标
            set_comp: 集合推导式节点
            parent: 父节点

        Returns:
            转换后的语句列表
        """
        new_stmts = []

        # 1. 初始化结果集合：result = set()
        from ..ir.expressions.literals import IRSet

        empty_set = IRSet()
        empty_set.parent = parent
        empty_set.elements = []

        init_assign = IRAssign()
        cloned_target = self._clone_name(target)
        init_assign.target_exprs = [cloned_target]
        init_assign.value = empty_set
        init_assign.parent = parent
        cloned_target.parent = init_assign
        empty_set.parent = init_assign
        if set_comp.source_line is not None:
            init_assign.source_line = set_comp.source_line
        new_stmts.append(init_assign)

        # 2. 构建嵌套的 for 循环（与列表推导式类似，但使用 add 而不是 append）
        loop_body = self._build_set_comp_loop_body(
            set_comp.generators, set_comp.elt, target, parent, set_comp.source_line
        )

        new_stmts.extend(loop_body)

        return new_stmts

    def _build_set_comp_loop_body(
        self,
        generators: List,
        elt: IRNode,
        result_target: IRNode,
        parent: Optional[IRNode],
        source_line: Optional[int],
    ) -> List[IRNode]:
        """构建集合推导式的循环体（与列表推导式类似，但使用 add）"""
        if not generators:
            return self._build_element_add(elt, result_target, parent, source_line)

        gen = generators[0]
        remaining_generators = generators[1:]

        iter_expr = gen.iter
        if contains_await(iter_expr):
            iter_temp_var = self._generate_temp_var()
            iter_assign_stmts = self._create_temp_assignment(
                iter_temp_var, iter_expr, parent
            )
            iter_expr = IRName(id=iter_temp_var)
            iter_expr.parent = parent
        else:
            iter_assign_stmts = []

        for_each = IRForEach()
        for_each.var = gen.target
        for_each.iter_expr = iter_expr
        for_each.parent = parent
        if source_line is not None:
            for_each.source_line = source_line

        gen.target.parent = for_each
        iter_expr.parent = for_each

        loop_body = IRStmtBlock()
        loop_body.parent = for_each
        for_each.body = loop_body

        if gen.ifs:
            cond_assign_stmts, if_stmt = self._build_set_condition_check(
                gen.ifs,
                remaining_generators,
                elt,
                result_target,
                loop_body,
                source_line,
            )
            # 先添加条件赋值语句（在 if 之前）
            loop_body.statements.extend(cond_assign_stmts)
            if if_stmt is not None:
                loop_body.statements.append(if_stmt)
        else:
            if remaining_generators:
                nested_loops = self._build_set_comp_loop_body(
                    remaining_generators, elt, result_target, loop_body, source_line
                )
                loop_body.statements.extend(nested_loops)
            else:
                append_stmts = self._build_element_add(
                    elt, result_target, loop_body, source_line
                )
                loop_body.statements.extend(append_stmts)

        result = []
        result.extend(iter_assign_stmts)
        result.append(for_each)

        return result

    def _build_set_condition_check(
        self,
        conditions: List,
        remaining_generators: List,
        elt: IRNode,
        result_target: IRNode,
        parent: Optional[IRNode],
        source_line: Optional[int],
    ) -> tuple[List[IRNode], Optional[IRIf]]:
        """构建集合推导式的条件检查"""
        if not conditions:
            return [], None

        condition = conditions[0]
        remaining_conditions = conditions[1:]

        if contains_await(condition):
            # 使用 _create_assignment_with_await 来避免创建多余的临时变量
            cond_temp_var = self._generate_temp_var()
            cond_temp_name = IRName(id=cond_temp_var)
            cond_temp_name.parent = parent
            cond_assign_stmts = self._create_assignment_with_await(
                cond_temp_name, condition, parent
            )
            cond_expr = IRName(id=cond_temp_var)
            cond_expr.parent = parent
        else:
            cond_assign_stmts = []
            cond_expr = condition
            cond_expr.parent = parent

        if_stmt = IRIf()
        if_stmt.test = cond_expr
        if_stmt.parent = parent
        if source_line is not None:
            if_stmt.source_line = source_line

        then_body = IRStmtBlock()
        then_body.parent = if_stmt
        if_stmt.then_body = then_body

        # 注意：条件赋值语句不应该放在 then_body 中，应该在 if 之前执行
        # 所以这里不再添加 cond_assign_stmts 到 then_body

        if remaining_conditions:
            nested_cond_stmts, nested_if = self._build_set_condition_check(
                remaining_conditions,
                remaining_generators,
                elt,
                result_target,
                then_body,
                source_line,
            )
            # 嵌套条件的赋值语句应该放在 then_body 中（在 if 之前）
            then_body.statements.extend(nested_cond_stmts)
            if nested_if:
                then_body.statements.append(nested_if)
        elif remaining_generators:
            nested_loops = self._build_set_comp_loop_body(
                remaining_generators, elt, result_target, then_body, source_line
            )
            then_body.statements.extend(nested_loops)
        else:
            # 没有剩余条件和生成器，添加元素（使用 add 方法）
            add_stmts = self._build_element_add(
                elt, result_target, then_body, source_line
            )
            then_body.statements.extend(add_stmts)

        return cond_assign_stmts, if_stmt

    def _transform_dict_comp_to_for_loop(
        self, target: IRNode, dict_comp: IRDictComp, parent: Optional[IRNode]
    ) -> List[IRNode]:
        """将异步字典推导式转换为 for 循环

        Args:
            target: 赋值目标
            dict_comp: 字典推导式节点
            parent: 父节点

        Returns:
            转换后的语句列表
        """
        new_stmts = []

        # 1. 初始化结果字典：result = {}
        from ..ir.expressions.literals import IRDict

        empty_dict = IRDict()
        empty_dict.parent = parent
        empty_dict.keys = []
        empty_dict.values = []

        init_assign = IRAssign()
        cloned_target = self._clone_name(target)
        init_assign.target_exprs = [cloned_target]
        init_assign.value = empty_dict
        init_assign.parent = parent
        cloned_target.parent = init_assign
        empty_dict.parent = init_assign
        if dict_comp.source_line is not None:
            init_assign.source_line = dict_comp.source_line
        new_stmts.append(init_assign)

        # 2. 构建嵌套的 for 循环
        loop_body = self._build_dict_comp_loop_body(
            dict_comp.generators,
            dict_comp.key,
            dict_comp.value,
            target,
            parent,
            dict_comp.source_line,
        )

        new_stmts.extend(loop_body)

        return new_stmts

    def _build_dict_comp_loop_body(
        self,
        generators: List,
        key: IRNode,
        value: IRNode,
        result_target: IRNode,
        parent: Optional[IRNode],
        source_line: Optional[int],
    ) -> List[IRNode]:
        """构建字典推导式的循环体

        由于循环体中包含 await，直接生成 while + 迭代器版本，而不是 for-each
        这样可以避免后续再次转换，并确保循环变量的作用域正确
        """
        if not generators:
            return self._build_dict_element_set(
                key, value, result_target, parent, source_line
            )

        gen = generators[0]
        remaining_generators = generators[1:]

        iter_expr = gen.iter
        if contains_await(iter_expr):
            iter_temp_var = self._generate_temp_var()
            iter_assign_stmts = self._create_temp_assignment(
                iter_temp_var, iter_expr, parent
            )
            iter_expr = IRName(id=iter_temp_var)
            iter_expr.parent = parent
        else:
            iter_assign_stmts = []

        # 由于循环体中包含 await，直接生成 while + 迭代器版本，而不是 for-each
        # 这样可以避免后续再次转换

        # 生成迭代器变量名
        iter_var = self._generate_temp_var()

        # 判断是否是元组解包
        is_tuple_unpacking = not isinstance(gen.target, IRName)

        # 如果是元组解包，需要生成临时变量存储 next() 的结果
        if is_tuple_unpacking:
            # 提取元组解包的变量名
            item_var = self._generate_temp_var()
            var_names = self._extract_var_names_from_target(gen.target)
        else:
            # 简单变量
            if isinstance(gen.target, IRName):
                item_var = gen.target.id
                var_names = [gen.target.id]
            else:
                # 不应该到这里，但为了安全
                item_var = self._generate_temp_var()
                var_names = []

        # 1. it = iter(iter_expr)
        iter_call = IRCall()
        iter_call.func = IRName(id="iter")
        iter_call.func.parent = iter_call
        iter_call.args = [iter_expr]
        iter_call.parent = parent
        iter_expr.parent = iter_call

        iter_assign = IRAssign()
        iter_assign.target_exprs = [IRName(id=iter_var)]
        iter_assign.target_exprs[0].parent = iter_assign
        iter_assign.value = iter_call
        iter_assign.parent = parent
        iter_call.parent = iter_assign
        if source_line is not None:
            iter_assign.source_line = source_line

        # 2. while True:
        while_stmt = IRWhile()
        while_stmt.test = IRConstant(value=True)
        while_stmt.test.parent = while_stmt
        while_stmt.parent = parent
        if source_line is not None:
            while_stmt.source_line = source_line

        # 创建 while 循环体
        loop_body = IRStmtBlock()
        loop_body.parent = while_stmt
        while_stmt.body = loop_body

        # 3. item = next(it, None) 或 x = next(it, None)
        next_call = IRCall()
        next_call.func = IRName(id="next")
        next_call.func.parent = next_call
        next_call.args = [IRName(id=iter_var), IRConstant(value=None)]
        next_call.args[0].parent = next_call
        next_call.args[1].parent = next_call
        next_call.parent = loop_body

        item_assign = IRAssign()
        item_assign.target_exprs = [IRName(id=item_var)]
        item_assign.target_exprs[0].parent = item_assign
        item_assign.value = next_call
        item_assign.parent = loop_body
        next_call.parent = item_assign
        if source_line is not None:
            item_assign.source_line = source_line

        # 对于字典推导式，检查循环变量是否在 key 表达式中使用
        # 如果使用，标记为需要提升为状态变量（因为会在 await 之后使用）
        if self._var_used_in_expr(item_var, key):
            item_assign.set_extension_param("promote_to_state_var", True)

        loop_body.statements.append(item_assign)

        # 4. if not item: break
        if_stmt = IRIf()
        if_stmt.parent = loop_body

        # not item
        not_op = IRUnaryOp()
        not_op.op = "not"
        not_op.operand = IRName(id=item_var)
        not_op.operand.parent = not_op
        not_op.parent = if_stmt
        if_stmt.test = not_op

        # break
        if_stmt.then_body = IRStmtBlock()
        if_stmt.then_body.parent = if_stmt
        break_stmt = IRBreak()
        break_stmt.parent = if_stmt.then_body
        if source_line is not None:
            break_stmt.source_line = source_line
        if_stmt.then_body.statements.append(break_stmt)

        if source_line is not None:
            if_stmt.source_line = source_line
        loop_body.statements.append(if_stmt)

        # 5. 如果是元组解包，使用下标操作替代解包语法
        if is_tuple_unpacking:
            from ..ir.expressions.access import IRSubscript

            # 为每个变量生成下标赋值：key = item[0], value = item[1], ...
            for idx, var_name in enumerate(var_names):
                # 创建下标表达式：item[idx]
                subscript = IRSubscript()
                subscript.value = IRName(id=item_var)
                subscript.value.parent = subscript
                subscript.slice = IRConstant(value=idx)
                subscript.slice.parent = subscript
                subscript.parent = loop_body

                # 创建赋值：var_name = item[idx]
                var_assign = IRAssign()
                var_assign.target_exprs = [IRName(id=var_name)]
                var_assign.target_exprs[0].parent = var_assign
                var_assign.value = subscript
                subscript.parent = var_assign
                var_assign.parent = loop_body
                if source_line is not None:
                    var_assign.source_line = source_line

                loop_body.statements.append(var_assign)

        # 处理条件
        if gen.ifs:
            # 有条件，需要先检查条件
            cond_assign_stmts, if_stmt = self._build_dict_condition_check(
                gen.ifs,
                remaining_generators,
                key,
                value,
                result_target,
                loop_body,
                source_line,
            )
            # 先添加条件赋值语句（在 if 之前）
            loop_body.statements.extend(cond_assign_stmts)
            if if_stmt is not None:
                loop_body.statements.append(if_stmt)
        else:
            # 无条件，直接处理剩余生成器或元素
            if remaining_generators:
                # 还有剩余生成器，递归处理
                nested_loops = self._build_dict_comp_loop_body(
                    remaining_generators,
                    key,
                    value,
                    result_target,
                    loop_body,
                    source_line,
                )
                loop_body.statements.extend(nested_loops)
            else:
                # 没有剩余生成器，添加元素
                set_stmts = self._build_dict_element_set(
                    key, value, result_target, loop_body, source_line
                )
                loop_body.statements.extend(set_stmts)

        # 组合语句：先处理迭代对象（如果有 await），然后添加迭代器初始化和 while 循环
        result = []
        result.extend(iter_assign_stmts)
        result.append(iter_assign)  # it = iter(...)
        result.append(while_stmt)  # while True: ...

        return result

    def _build_dict_condition_check(
        self,
        conditions: List,
        remaining_generators: List,
        key: IRNode,
        value: IRNode,
        result_target: IRNode,
        parent: Optional[IRNode],
        source_line: Optional[int],
    ) -> tuple[List[IRNode], Optional[IRIf]]:
        """构建字典推导式的条件检查"""
        if not conditions:
            return [], None

        condition = conditions[0]
        remaining_conditions = conditions[1:]

        if contains_await(condition):
            # 使用 _create_assignment_with_await 来避免创建多余的临时变量
            cond_temp_var = self._generate_temp_var()
            cond_temp_name = IRName(id=cond_temp_var)
            cond_temp_name.parent = parent
            cond_assign_stmts = self._create_assignment_with_await(
                cond_temp_name, condition, parent
            )
            cond_expr = IRName(id=cond_temp_var)
            cond_expr.parent = parent
        else:
            cond_assign_stmts = []
            cond_expr = condition
            cond_expr.parent = parent

        if_stmt = IRIf()
        if_stmt.test = cond_expr
        if_stmt.parent = parent
        if source_line is not None:
            if_stmt.source_line = source_line

        then_body = IRStmtBlock()
        then_body.parent = if_stmt
        if_stmt.then_body = then_body

        # 注意：条件赋值语句不应该放在 then_body 中，应该在 if 之前执行
        # 所以这里不再添加 cond_assign_stmts 到 then_body

        if remaining_conditions:
            nested_cond_stmts, nested_if = self._build_dict_condition_check(
                remaining_conditions,
                remaining_generators,
                key,
                value,
                result_target,
                then_body,
                source_line,
            )
            # 嵌套条件的赋值语句应该放在 then_body 中（在 if 之前）
            then_body.statements.extend(nested_cond_stmts)
            if nested_if:
                then_body.statements.append(nested_if)
        elif remaining_generators:
            nested_loops = self._build_dict_comp_loop_body(
                remaining_generators,
                key,
                value,
                result_target,
                then_body,
                source_line,
            )
            then_body.statements.extend(nested_loops)
        else:
            set_stmts = self._build_dict_element_set(
                key, value, result_target, then_body, source_line
            )
            then_body.statements.extend(set_stmts)

        return cond_assign_stmts, if_stmt

    def _build_dict_element_set(
        self,
        key: IRNode,
        value: IRNode,
        result_target: IRNode,
        parent: Optional[IRNode],
        source_line: Optional[int],
    ) -> List[IRNode]:
        """构建字典元素设置语句：result[key] = value"""
        stmts = []

        # 处理 key
        if contains_await(key):
            # 使用 _create_assignment_with_await 来正确处理 await 表达式
            # 这与 value 的处理方式保持一致，确保 await 结果被正确赋值
            key_temp_var = self._generate_temp_var()
            key_temp_name = IRName(id=key_temp_var)
            key_temp_name.parent = parent
            key_assign_stmts = self._create_assignment_with_await(
                key_temp_name, key, parent
            )
            stmts.extend(key_assign_stmts)
            key_expr = key_temp_name
        else:
            key_expr = key
            key_expr.parent = parent

        # 处理 value
        if contains_await(value):
            # 使用 _create_assignment_with_await 来正确处理 await 表达式
            value_temp_var = self._generate_temp_var()
            value_temp_name = IRName(id=value_temp_var)
            value_temp_name.parent = parent
            value_assign_stmts = self._create_assignment_with_await(
                value_temp_name, value, parent
            )
            stmts.extend(value_assign_stmts)
            value_expr = value_temp_name
        else:
            value_expr = value
            value_expr.parent = parent

        # 创建下标赋值：result[key] = value
        subscript = IRSubscript()
        subscript.value = self._clone_name(result_target)
        subscript.value.parent = subscript
        subscript.slice = key_expr
        key_expr.parent = subscript
        subscript.parent = parent

        assign = IRAssign()
        assign.target_exprs = [subscript]
        subscript.parent = assign
        assign.value = value_expr
        value_expr.parent = assign
        assign.parent = parent
        if source_line is not None:
            assign.source_line = source_line

        stmts.append(assign)

        return stmts

    def _transform_literal_assignment(self, stmt: IRAssign) -> List[IRNode]:
        """转换包含 await 的字面量赋值语句

        将异步字面量转换为顺序语句：
        result = [await get_value(1), await get_value(2), await get_value(3)]
        =>
        result = []
        __temp_0 = await get_value(1)
        result.append(__temp_0)
        __temp_1 = await get_value(2)
        result.append(__temp_1)
        __temp_2 = await get_value(3)
        result.append(__temp_2)

        支持：
        1. 列表字面量：result = [await f(), await g(), ...]
        2. 字典字面量：result = {await k(): await v(), ...}
        3. 集合字面量：result = {await f(), await g(), ...}
        4. 元组字面量：result = (await f(), await g(), ...)

        Args:
            stmt: 赋值语句节点

        Returns:
            转换后的语句列表
        """
        literal_expr = stmt.value
        target = stmt.get_target_expr()

        if target is None:
            # 无法获取目标，返回原语句
            return [stmt]

        if isinstance(literal_expr, IRList):
            new_stmts = self._transform_list_literal_assignment(
                target, literal_expr, stmt.parent, stmt.annotation
            )
        elif isinstance(literal_expr, IRDict):
            new_stmts = self._transform_dict_literal_assignment(
                target, literal_expr, stmt.parent, stmt.annotation
            )
        elif isinstance(literal_expr, IRSet):
            new_stmts = self._transform_set_literal_assignment(
                target, literal_expr, stmt.parent, stmt.annotation
            )
        elif isinstance(literal_expr, IRTuple):
            new_stmts = self._transform_tuple_literal_assignment(
                target, literal_expr, stmt.parent, stmt.annotation
            )
        else:
            # 不应该到这里
            return [stmt]

        return new_stmts

    def _transform_list_literal_assignment(
        self,
        target: IRNode,
        list_literal: IRList,
        parent: Optional[IRNode],
        annotation: Optional[str],
    ) -> List[IRNode]:
        """转换包含 await 的列表字面量赋值

        Args:
            target: 赋值目标（result）
            list_literal: 列表字面量节点
            parent: 父节点
            annotation: 类型注解

        Returns:
            转换后的语句列表
        """
        new_stmts = []

        # 1. 初始化结果列表：result = []
        empty_list = IRList()
        empty_list.parent = parent
        empty_list.elements = []

        init_assign = IRAssign()
        cloned_target = self._clone_name(target)
        init_assign.target_exprs = [cloned_target]
        init_assign.value = empty_list
        init_assign.parent = parent
        init_assign.annotation = annotation
        cloned_target.parent = init_assign
        empty_list.parent = init_assign
        if list_literal.source_line is not None:
            init_assign.source_line = list_literal.source_line
        new_stmts.append(init_assign)

        # 2. 依次处理每个元素，按顺序添加
        for element in list_literal.elements:
            # 构建 append 语句（会自动处理 await）
            append_stmts = self._build_element_append(
                element, target, parent, list_literal.source_line
            )
            new_stmts.extend(append_stmts)

        return new_stmts

    def _transform_dict_literal_assignment(
        self,
        target: IRNode,
        dict_literal: IRDict,
        parent: Optional[IRNode],
        annotation: Optional[str],
    ) -> List[IRNode]:
        """转换包含 await 的字典字面量赋值

        Args:
            target: 赋值目标（result）
            dict_literal: 字典字面量节点
            parent: 父节点
            annotation: 类型注解

        Returns:
            转换后的语句列表
        """
        new_stmts = []

        # 1. 初始化结果字典：result = {}
        empty_dict = IRDict()
        empty_dict.parent = parent
        empty_dict.keys = []
        empty_dict.values = []

        init_assign = IRAssign()
        cloned_target = self._clone_name(target)
        init_assign.target_exprs = [cloned_target]
        init_assign.value = empty_dict
        init_assign.parent = parent
        init_assign.annotation = annotation
        cloned_target.parent = init_assign
        empty_dict.parent = init_assign
        if dict_literal.source_line is not None:
            init_assign.source_line = dict_literal.source_line
        new_stmts.append(init_assign)

        # 2. 依次处理每个键值对，按顺序添加
        for key, value in zip(dict_literal.keys, dict_literal.values):
            # 构建字典元素设置：result[key] = value（会自动处理 await）
            set_stmts = self._build_dict_element_set(
                key, value, target, parent, dict_literal.source_line
            )
            new_stmts.extend(set_stmts)

        return new_stmts

    def _transform_set_literal_assignment(
        self,
        target: IRNode,
        set_literal: IRSet,
        parent: Optional[IRNode],
        annotation: Optional[str],
    ) -> List[IRNode]:
        """转换包含 await 的集合字面量赋值

        Args:
            target: 赋值目标（result）
            set_literal: 集合字面量节点
            parent: 父节点
            annotation: 类型注解

        Returns:
            转换后的语句列表
        """
        new_stmts = []

        # 1. 初始化结果集合：result = set()
        empty_set = IRSet()
        empty_set.parent = parent
        empty_set.elements = []

        init_assign = IRAssign()
        cloned_target = self._clone_name(target)
        init_assign.target_exprs = [cloned_target]
        init_assign.value = empty_set
        init_assign.parent = parent
        init_assign.annotation = annotation
        cloned_target.parent = init_assign
        empty_set.parent = init_assign
        if set_literal.source_line is not None:
            init_assign.source_line = set_literal.source_line
        new_stmts.append(init_assign)

        # 2. 依次处理每个元素，按顺序添加
        for element in set_literal.elements:
            # 构建 add 语句（会自动处理 await）
            add_stmts = self._build_element_add(
                element, target, parent, set_literal.source_line
            )
            new_stmts.extend(add_stmts)

        return new_stmts

    def _transform_tuple_literal_assignment(
        self,
        target: IRNode,
        tuple_literal: IRTuple,
        parent: Optional[IRNode],
        annotation: Optional[str],
    ) -> List[IRNode]:
        """转换包含 await 的元组字面量赋值

        注意：元组是不可变的，所以需要先收集所有元素，然后一次性创建元组。
        这需要按顺序等待所有 await 表达式。

        Args:
            target: 赋值目标（result）
            tuple_literal: 元组字面量节点
            parent: 父节点
            annotation: 类型注解

        Returns:
            转换后的语句列表
        """
        new_stmts = []

        # 对于元组，我们需要先收集所有元素到临时变量，然后创建元组
        # 1. 先提取所有 await 表达式并创建临时变量
        temp_vars = []
        for element in tuple_literal.elements:
            if contains_await(element):
                # 提取 await 表达式
                temp_var = self._generate_temp_var()
                temp_name = IRName(id=temp_var)
                temp_name.parent = parent
                temp_assign_stmts = self._create_assignment_with_await(
                    temp_name, element, parent
                )
                new_stmts.extend(temp_assign_stmts)
                temp_vars.append(temp_name)
            else:
                # 不包含 await，直接使用原表达式
                temp_vars.append(element)

        # 2. 创建元组赋值：result = (__temp_0, __temp_1, ...)
        new_tuple = IRTuple()
        new_tuple.parent = parent
        new_tuple.elements = temp_vars
        for element in temp_vars:
            if isinstance(element, IRNode):
                element.parent = new_tuple

        assign = IRAssign()
        cloned_target = self._clone_name(target)
        assign.target_exprs = [cloned_target]
        assign.value = new_tuple
        assign.parent = parent
        assign.annotation = annotation
        cloned_target.parent = assign
        new_tuple.parent = assign
        if tuple_literal.source_line is not None:
            assign.source_line = tuple_literal.source_line
        new_stmts.append(assign)

        return new_stmts
